package com.example.smart_city_0829.activity.lawyer_consultation;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.smart_city_0829.R;
import com.example.smart_city_0829.adapter.BaseViewPagerAdapter;
import com.example.smart_city_0829.base.BaseActivity;
import com.example.smart_city_0829.base.CommonAdapter;
import com.example.smart_city_0829.entity.lawyer_onsultation.Consultation;
import com.example.smart_city_0829.entity.lawyer_onsultation.LawyerBanner;
import com.example.smart_city_0829.entity.lawyer_onsultation.LawyerList;
import com.example.smart_city_0829.entity.lawyer_onsultation.LawyerTop;
import com.example.smart_city_0829.entity.lawyer_onsultation.LegalExpertiseList;
import com.example.smart_city_0829.retrofit.NetCallBack;
import com.example.smart_city_0829.utils.Constant;
import com.example.smart_city_0829.view.MaxSizeGv;
import com.example.smart_city_0829.view.MaxSizeLv;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import retrofit2.Call;
import retrofit2.Response;

public class LawyerMainActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private EditText searchEt;
    private Banner banner;
    private MaxSizeGv myQuesGv;
    private MaxSizeLv goodLv;
    private Button lawyerMoreBt;
    private ViewPager goodAtVp;

    private RadioGroup rg;
    private RadioButton rb1;
    private RadioButton rb2;


    public static LegalExpertiseList legalExpertiseList;
    private int myConsultationPageNum = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_lawyer_main;
    }

    @Override
    protected void initView() {
        searchEt = (EditText) findViewById(R.id.search_et);
        banner = (Banner) findViewById(R.id.banner);
        goodAtVp = (ViewPager) findViewById(R.id.goodAt_vp);
        myQuesGv = (MaxSizeGv) findViewById(R.id.my_ques_gv);
        goodLv = (MaxSizeLv) findViewById(R.id.good_lv);
        lawyerMoreBt = (Button) findViewById(R.id.lawyer_more_bt);
        rg = (RadioGroup) findViewById(R.id.rg);
        rb1 = (RadioButton) findViewById(R.id.rb1);
        rb2 = (RadioButton) findViewById(R.id.rb2);
    }

    @Override
    protected void initData() {
        api.getLawyerMainBanner().enqueue(new NetCallBack<LawyerBanner>() {
            @Override
            public void onResponse(Call<LawyerBanner> call, Response<LawyerBanner> response) {
                if (response.body() == null) return;

                final List<LawyerBanner.DataBean> data = response.body().getData();
                banner.setBannerTitles(data.stream()
                        .map(LawyerBanner.DataBean::getTitle)
                        .collect(Collectors.toList()));
                banner.setImages(data.stream()
                        .map(LawyerBanner.DataBean::getImgUrl)
                        .collect(Collectors.toList()));
                banner.start();
                banner.startAutoPlay();
            }
        });
        //获取律师专长列表
        api.getLegalExpertiseList().enqueue(new NetCallBack<LegalExpertiseList>() {
            @Override
            public void onResponse(Call<LegalExpertiseList> call, Response<LegalExpertiseList> response) {
                if (response.body() == null) return;
                legalExpertiseList = response.body();
                final List<View> pages = new ArrayList<>();
                final GridView gv1 = new MaxSizeGv(context);
                gv1.setNumColumns(4);
                gv1.setAdapter(new LegalAdapter(response.body().getRows().subList(0, 8), context));
                gv1.setOnItemClickListener(LawyerMainActivity.this);
                pages.add(gv1);
                final GridView gv2 = new MaxSizeGv(context);
                gv2.setNumColumns(4);
                gv2.setAdapter(new LegalAdapter(response.body().getRows().subList(8, 16), context));
                gv2.setOnItemClickListener(LawyerMainActivity.this);
                pages.add(gv2);
                goodAtVp.setAdapter(new BaseViewPagerAdapter(pages, context));
            }
        });
        //获取我的咨询列表
        api.getMyConsultation(4, myConsultationPageNum).enqueue(new NetCallBack<Consultation>() {
            @Override
            public void onResponse(Call<Consultation> call, Response<Consultation> response) {
                if (response.body() == null) return;

                final List<Consultation.RowsBean> rows = response.body().getRows();
                myQuesGv.setAdapter(new MyConsultationAdapter(rows, context));
            }
        });

        api.getTopLawyer(null, null).enqueue(new NetCallBack<LawyerTop>() {
            @Override
            public void onResponse(@NonNull Call<LawyerTop> call, @NonNull Response<LawyerTop> response) {
                if (response.body() == null) return;
                goodLv.setAdapter(new TopLvAdapter(response.body().getData(), context));
            }
        });
    }

    @Override
    protected void initEvent() {
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        banner.setDelayTime(3000);
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object o, ImageView imageView) {
                Glide.with(context)
                        .load(Constant.BASE_URL + o)
                        .transform(new RoundedCorners(8),new RoundedCorners(8))
                        .into(imageView);
            }
        });

        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                final String s = searchEt.getText().toString();
                searchEt.setText("");
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    final Intent intent = new Intent(context, SearchResultActivity.class);
                    intent.putExtra("keyName", s);
                    startActivity(intent);
                    return true;
                }
                return false;
            }
        });

        goodAtVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (position == 0) {
                    rb1.setChecked(true);
                } else if (position == 1) {
                    rb2.setChecked(true);
                }
            }

            @Override
            public void onPageSelected(int position) {
                //ignore
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                //ignore
            }
        });

        myQuesGv.setOnItemClickListener((parent, view, position, id) -> {
            final Consultation.RowsBean item = (Consultation.RowsBean) parent.getAdapter().getItem(position);

            final Intent intent = new Intent(context, ConsultationDetailActivity.class);
            intent.putExtra("data",gson.toJson(item));
            startActivity(intent);
        });

        lawyerMoreBt.setOnClickListener((v) -> migrateTo(LawyerListActivity.class));
    }

    @Override
    protected String getActionBarTitle() {
        return "法律咨询";
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final Intent intent = new Intent(context, LegalExpertiseListActivity.class);
        intent.putExtra("LegalExpertiseListData", gson.toJson(legalExpertiseList));
        startActivity(intent);
    }


    private class TopLvAdapter extends CommonAdapter<LawyerTop.DataBean, CommonAdapter.CommListViewHolder2> {

        public TopLvAdapter(List<LawyerTop.DataBean> data, Context context) {
            super(data, context);
        }

        @Override
        protected void setData(LawyerTop.DataBean data, int position, CommListViewHolder2 viewHolder, View convertView, Context context) {
            Glide.with(context)
                    .load(Constant.BASE_URL + data.getAvatarUrl())
                    .into(viewHolder.imageView);

            viewHolder.name.setText(String.valueOf(data.getName()));
            viewHolder.workYearsTv.setText("从业" + (Calendar.getInstance().get(Calendar.YEAR) - Integer.parseInt(data.getWorkStartAt().substring(0, 4))) + "年");
            viewHolder.goodAtTv.setText("法律专长：" + data.getLegalExpertiseName());
            viewHolder.serviceTimesTv.setText("咨询人数：" + data.getServiceTimes());
            viewHolder.favorableRateTv.setText("好评率：" + data.getFavorableRate());

            viewHolder.quesBt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Intent intent = new Intent(context, LawyerDetailActivity.class);
                    intent.putExtra("lawyerData", gson.toJson(data));
                    context.startActivity(intent);
                }
            });
        }

        @Override
        protected CommListViewHolder2 getViewHolder() {
            return new CommListViewHolder2();
        }

        @Override
        protected void initView(CommListViewHolder2 viewHolder, View convertView) {
            viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
            viewHolder.name = (TextView) convertView.findViewById(R.id.name);
            viewHolder.workYearsTv = (TextView) convertView.findViewById(R.id.work_years_tv);
            viewHolder.goodAtTv = (TextView) convertView.findViewById(R.id.goodAt_tv);
            viewHolder.serviceTimesTv = (TextView) convertView.findViewById(R.id.serviceTimes_tv);
            viewHolder.favorableRateTv = (TextView) convertView.findViewById(R.id.favorableRate_tv);
            viewHolder.quesBt = (Button) convertView.findViewById(R.id.ques_bt);

        }

        @Override
        protected int getItemLayoutResourceId() {
            return R.layout.lawyer_list_item;
        }
    }

    private class LegalAdapter extends CommonAdapter<LegalExpertiseList.RowsBean, CommonAdapter.CommGridViewHolder> {

        public LegalAdapter(List<LegalExpertiseList.RowsBean> data, Context context) {
            super(data, context);
        }

        @Override
        protected void setData(LegalExpertiseList.RowsBean data, int position, CommGridViewHolder viewHolder, View convertView, Context context) {
            Glide.with(context)
                    .load(Constant.BASE_URL + data.getImgUrl())
                    .into(viewHolder.im);
            viewHolder.serverName.setText(data.getName());
        }

        @Override
        protected CommGridViewHolder getViewHolder() {
            return new CommGridViewHolder();
        }

        @Override
        protected void initView(CommGridViewHolder viewHolder, View convertView) {
            viewHolder.im = (ImageView) convertView.findViewById(R.id.im);
            viewHolder.serverName = (TextView) convertView.findViewById(R.id.server_name);
        }

        @Override
        protected int getItemLayoutResourceId() {
            return R.layout.server_list_item;
        }
    }


    class MyConsultationAdapter extends CommonAdapter<Consultation.RowsBean, GvViewHolder> {

        public MyConsultationAdapter(List<Consultation.RowsBean> data, Context context) {
            super(data, context);
        }

        @Override
        protected void setData(Consultation.RowsBean data, int position, GvViewHolder viewHolder, View convertView, Context context) {
            final String[] split = data.getImageUrls().split(",");
            if (split.length > 0) {
                Glide.with(context)
                        .load(Constant.BASE_URL + "prod-api" + split[0])
                        .into(viewHolder.im);
            }
        }

        @Override
        protected GvViewHolder getViewHolder() {
            return new GvViewHolder();
        }

        @Override
        protected void initView(GvViewHolder viewHolder, View convertView) {
            viewHolder.im = convertView.findViewById(R.id.im);
        }

        @Override
        protected int getItemLayoutResourceId() {
            return R.layout.im_item;
        }
    }

    static class GvViewHolder {
        ImageView im;
    }


}